package de.uni.leipzig.meddins.server;

import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.EventListener;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.util.EntityUtils;

public class NIOSocketServer {
	// org.apache.http.nio. muss importiert werden
	public static void main(String[] args) throws Exception {
		if (args.length < 1) {
			System.err.println("Please specify document root directory");
			System.exit(1);
		}
		HttpParams params = new SyncBasicHttpParams();
		params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
				.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
						8 * 1024)
				.setBooleanParameter(
						CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
				.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
				.setParameter(CoreProtocolPNames.ORIGIN_SERVER,
						"HttpComponents/1.1");

		HttpProcessor httpproc = new ImmutableHttpProcessor(
				new HttpResponseInterceptor[] { new ResponseDate(),
						new ResponseServer(), new ResponseContent(),
						new ResponseConnControl() });

		BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler(
				httpproc, new DefaultHttpResponseFactory(),
				new DefaultConnectionReuseStrategy(), params);

		// Set up request handlers
		HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
		reqistry.register("*", new HttpFileHandler(args[0]));

		handler.setHandlerResolver(reqistry);

		// Provide an event logger
		handler.setEventListener(new EventLogger());

		IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(
				handler, params);
		ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
		try {
			ioReactor.listen(new InetSocketAddress(8080));
			ioReactor.execute(ioEventDispatch);
		} catch (InterruptedIOException ex) {
			System.err.println("Interrupted");
		} catch (IOException e) {
			System.err.println("I/O error: " + e.getMessage());
		}
		System.out.println("Shutdown");
	}

	static class HttpFileHandler implements HttpRequestHandler {

		private final String docRoot;

		public HttpFileHandler(final String docRoot) {
			super();
			this.docRoot = docRoot;
		}

		public void handle(final HttpRequest request,
				final HttpResponse response, final HttpContext context)
				throws HttpException, IOException {

			String method = request.getRequestLine().getMethod()
					.toUpperCase(Locale.ENGLISH);
			if (!method.equals("GET") && !method.equals("HEAD")
					&& !method.equals("POST")) {
				throw new MethodNotSupportedException(method
						+ " method not supported");
			}

			if (request instanceof HttpEntityEnclosingRequest) {
				HttpEntity entity = ((HttpEntityEnclosingRequest) request)
						.getEntity();
				byte[] entityContent = EntityUtils.toByteArray(entity);
				System.out.println("Incoming entity content (bytes): "
						+ entityContent.length);
			}

			String target = request.getRequestLine().getUri();
			final File file = new File(this.docRoot, URLDecoder.decode(target,
					"UTF-8"));
			if (!file.exists()) {

				response.setStatusCode(HttpStatus.SC_NOT_FOUND);
				NStringEntity entity = new NStringEntity("<html><body><h1>File"
						+ file.getPath() + " not found</h1></body></html>",
						"UTF-8");
				entity.setContentType("text/html; charset=UTF-8");
				response.setEntity(entity);
				System.out.println("File " + file.getPath() + " not found");

			} else if (!file.canRead() || file.isDirectory()) {

				response.setStatusCode(HttpStatus.SC_FORBIDDEN);
				NStringEntity entity = new NStringEntity(
						"<html><body><h1>Access denied</h1></body></html>",
						"UTF-8");
				entity.setContentType("text/html; charset=UTF-8");
				response.setEntity(entity);
				System.out.println("Cannot read file " + file.getPath());

			} else {

				response.setStatusCode(HttpStatus.SC_OK);
				NFileEntity body = new NFileEntity(file, "text/html");
				response.setEntity(body);
				System.out.println("Serving file " + file.getPath());

			}
		}

	}

	static class EventLogger implements EventListener {

		public void connectionOpen(final NHttpConnection conn) {
			System.out.println("Connection open: " + conn);
		}

		public void connectionTimeout(final NHttpConnection conn) {
			System.out.println("Connection timed out: " + conn);
		}

		public void connectionClosed(final NHttpConnection conn) {
			System.out.println("Connection closed: " + conn);
		}

		public void fatalIOException(final IOException ex,
				final NHttpConnection conn) {
			System.err.println("I/O error: " + ex.getMessage());
		}

		public void fatalProtocolException(final HttpException ex,
				final NHttpConnection conn) {
			System.err.println("HTTP error: " + ex.getMessage());
		}

	}
}